package com.wsdc.messagedigest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*
    这就是你后退的理由？？？
 */

public class MainActivity extends AppCompatActivity {
    //MD5

    private String pw = "wsdc";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view) {
        switch (view.getId()){
            case R.id.md5://返回结果32位
                String str = md("MD5",pw);

                Log.d("flag", "click: MD5 " +str);

                break;


            case R.id.sha_1://返回40位
                String sha = md("SHA-1",pw);

                Log.d("flag", "click: SHA-1 " +sha);
                break;
        }
    }

    private String md(String mode, String pw) {
        //创建消息摘要的对象
        try {
            MessageDigest md = MessageDigest.getInstance(mode);

            md.update(pw.getBytes());

            byte[] digest = md.digest();

            //Log.d("flag", "md: " +digest.length);
            //Log.d("flag", "md: " +digest[0]);

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < digest.length; i++) {
                //1111
                int num = digest[i] & 0xff;

                if(num < 16){
                    builder.append(0);
                }

                String result = Integer.toHexString(num);

                builder.append(result);
            }

            return builder.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        return null;
    }
}
